<script setup lang="ts">
import { createEnterpriseAPI, getEnterpriseDetailAPI, getIndustryListAPI, updateEnterpriseAPI, uploadAPI } from '@/apis/enterprise';
import router from '@/router';
import type { EnterpriseDetail, Industry, UploadUserFile } from '@/types/enterprise';
import { validMobile } from '@/utils/validate';
import { ElMessage, type UploadRawFile, type UploadRequestOptions } from 'element-plus';
import { el } from 'element-plus/es/locales.mjs';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

// 获取路由传的企业id
const route = useRoute()
const id = ref('')
onMounted(()=>{
  const paramsId = route.query.id as string
  if(paramsId){
    getDetail(paramsId)
  }
})
const getDetail = async(id:string)=>{
  const res = await getEnterpriseDetailAPI(id)
  const { businessLicenseId, businessLicenseUrl, contact, contactNumber, industryCode, legalPerson, name, registeredAddress, businessLicenseName } = res.data
  // 数据回写
  addForm.value = {
    name, legalPerson, registeredAddress, industryCode, contact, contactNumber, businessLicenseUrl, businessLicenseId
  }
  fileList.value.push({
    name: businessLicenseName, 
    url: businessLicenseUrl, 
  })
}
const addForm = ref({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: '', // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: '' // 营业执照id
}) 
const industryList = ref<Industry[]>([]) // 可选行业列表
const getIndustryList = async () =>{
  const res = await getIndustryListAPI()
  industryList.value = res.data
}
getIndustryList()

// 上传营业执照的回调
const fileList = ref<UploadUserFile[]>([]) // 营业执照列表
const uploadRequest = async (options: UploadRequestOptions): Promise<any> => {
  //包装formData对象
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type','businessLicense')
  const res = await uploadAPI(fd)

  addForm.value.businessLicenseId = res.data.id!
  addForm.value.businessLicenseUrl = res.data.url
  
    // 单独校验表单，清除错误信息
    formRef.value.validateField('businessLicenseId')

}
// 上传之前对文件做校验
const onExceed = () =>{
  ElMessage({
    type: 'error',
    message: '最多上传一张图片'
  })
}
const beforeUpload =(rawFile: UploadRawFile)=>{
  //文件类型
  const isAllowType = ['image/jpeg', 'image/png', 'image/jpg'].includes(rawFile.type)
  if(!isAllowType){
    ElMessage({
      type: 'error',
      message: '格式不正确,请上传图片文件'
    })
    return false
  }
  // 文件大小
  const isLt5M = rawFile.size / 1024 / 1024 < 5
  if(!isLt5M){
    ElMessage({
      type: 'error',
      message: '文件大小不能超过5M'
    })
    return false
  }
  return true
}

// 校验整个表单
const formRef = ref()
// 校验规则
const addRules = ref({
  name: [
    { required: true, message: '企业名称为必填', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '法人为必填', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '注册地址为必填', trigger: 'blur' }
  ],
  industryCode: [
    { required: true, message: '所在行业为必填', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '企业联系人为必填', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
    { validator: validMobile, trigger: 'blur' }
  ],
  businessLicenseId: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ]
}) 
const confirmSubmit = ()=>{
  formRef.value.validate(async(valid: boolean) => {
    if(valid){
      if(id.value){
        await updateEnterpriseAPI({
          ...addForm.value,
          id:id.value
        })
      }else{
        await createEnterpriseAPI(addForm.value)
      }

      ElMessage({
        type: 'success',
        message: '添加成功'
      })
      router.back()
    }else{
      return
    }
  })
}
// 重置表单
const resetForm = ()=>{
  formRef.value.resetFields()
}

</script>


<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="formRef" label-width="100px" :rules="addRules" :model="addForm">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option v-for="item in industryList" :key="item.industryCode" :value="item.industryCode"
                :label="item.industryName" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
                <el-upload
                action="#" 
                :file-list="fileList"
                list-type="picture" 
                :http-request="uploadRequest"
                :limit="1"
                :before-upload="beforeUpload"
                :on-exceed="onExceed"
                >
                    <el-button 
                    type="primary"
                    size="small"
                    >上传营业执照</el-button>
                    <div slot="tip" class="el-upload__tip">支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M</div>
                </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>